package com.wall.haven.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wall.haven.config.SystemConfigCache;
import com.wall.haven.dto.AcknowledgementUserDTO;
import com.wall.haven.dto.Notice;
import com.wall.haven.dto.SystemDataDTO;
import com.wall.haven.dto.UpdateLogDTO;
import com.wall.haven.entity.SystemConfig;
import com.wall.haven.entity.UpdateLog;
import com.wall.haven.enums.ConfigKey;
import com.wall.haven.util.AESUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SystemService {

    @Resource
    private SystemConfigCache systemConfigCache;

    @Resource
    private ISystemConfigService systemConfigService;

    @Resource
    private IAcknowledgementUserService acknowledgementUserService;


    @Resource
    private IUpdateLogService updateLogService;

    /**
     * 获取系统相关信息
     *
     * @return
     */
    public SystemDataDTO systemData() {
        SystemConfig notice = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                .eq(SystemConfig::getConfigKey, ConfigKey.NOTICE.name()));
        List<AcknowledgementUserDTO> users = acknowledgementUserService.list().stream()
                .map(user -> new AcknowledgementUserDTO(user.getAvatar(), user.getName())).collect(Collectors.toList());
        List<UpdateLogDTO> updateLogs = updateLogService.list(Wrappers.<UpdateLog>lambdaQuery()
                .orderByDesc(UpdateLog::getReleaseTime)).stream().map(UpdateLogDTO::new).collect(Collectors.toList());
        return new SystemDataDTO(
                notice == null ? null : new Notice(notice.getConfigValue(),
                notice.getGmtCreate().atZone(ZoneId.of("Asia/Shanghai")).toEpochSecond()),
                systemConfigService.getDefaultAvatar(),
                users, updateLogs,
                AESUtil.encrypt(systemConfigCache.getRsaPublicKey(), systemConfigCache.getAesKey()),
                systemConfigCache.getAesKey(),
                systemConfigCache.isShowSecretKey() ?
                AESUtil.encrypt(systemConfigCache.getSecretKey(), systemConfigCache.getAesKey())
                : null);
    }
}
